//
//  MainViewController.swift
//  PhotoLine
//
//  Created by 吴帅 on 2017/11/20.
//  Copyright © 2017年 PhotoLine. All rights reserved.
//

import UIKit
import Photos
import Alamofire

class MainViewController: BaseViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    var client : OSSClient?;
    // MARK: - LiftCycle
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.view.backgroundColor = UIColor.white;
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.add, target: self, action: #selector(add))
        getToken()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - UIImagePickerControllerDelegate
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image : UIImage = info["UIImagePickerControllerOriginalImage"] as! UIImage;
        let data = UIImagePNGRepresentation(image)
//        a(data: data!);
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        
    }
    
    func a(data: Data, name: String) {
        let put = OSSPutObjectRequest.init();
        put.bucketName = "photo-line";
        put.objectKey = "image/2017/" + name + ".jpg";
        put.uploadingData = data;
        
        
        let putTask = client?.putObject(put);
        putTask?.continue({ (task) -> Any? in
            print(task.error);
            return nil;
        })
        putTask?.waitUntilFinished()
    }
    
    // MARK: - Private
    func add() {
//        let p = UIImagePickerController.init();
//        p.sourceType = UIImagePickerControllerSourceType.photoLibrary;
//        self.present(p, animated: true, completion: nil);
//        p.delegate = self;
        getAllAssetInPhotoAblumWithAscending();
    }
    
    func getAllAssetInPhotoAblumWithAscending() -> Void {

        let option = PHFetchOptions();
        option.sortDescriptors = NSArray.init(object: NSSortDescriptor.init(key: "creationDate", ascending: true)) as? [NSSortDescriptor];
        let result = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: option);
        result.enumerateObjects ({ (obj, idx, stop) in
            let asset = obj as PHAsset;
            print("照片名%@:%@", asset.value(forKey: "filename")!, asset.creationDate!);
            let size =  CGSize.init(width: asset.pixelWidth, height: asset.pixelHeight);
            let op = PHImageRequestOptions();
            op.isSynchronous = true;
            PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: PHImageContentMode.default, options: op, resultHandler: { (result, info) in
                self.a(data: UIImageJPEGRepresentation(result!, 0.9)!, name: asset.value(forKey: "filename") as! String);
            })
        });
        
    }
    
    func getToken() {
        Alamofire.request("http://39.106.104.91:8080/maven-springmvc/token/get", method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            if let json : NSDictionary = response.result.value as? NSDictionary {
//                if (json["status"] as! Int == 200) {
                    let credential = OSSStsTokenCredentialProvider.init(accessKeyId: (json["AccessKeyId"] as! String), secretKeyId: (json["AccessKeySecret"] as! String), securityToken: (json["SecurityToken"] as! String))
                    let conf = OSSClientConfiguration.init();
                    conf.maxRetryCount = 3;
                    conf.timeoutIntervalForRequest = 30;
                    conf.timeoutIntervalForResource = 24 * 60 * 60;
                    
                    self.client = OSSClient.init(endpoint: "https://oss-cn-beijing.aliyuncs.com", credentialProvider: credential!, clientConfiguration: conf);
//                }
            }
        };
    }
    
    // MARK: - Public

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
